﻿using HtmlAgilityPack;
using Ozner.Common;
using Ozner.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace Ozner.BLL
{
    public class TopBLL:BaseBLL
    {
        private string URL = "/top.aspx";

        public BaseResult<List<Menu>> GetTopMenu()
        {
            try
            {
                BaseResult<List<Menu>> br = GetLoginedDocument<List<Menu>>(URL);
                if (br.Code == Code.OK)
                {
                    HtmlDocument doc = br.OtherInfo as HtmlDocument;
                    HtmlNodeCollection hns = doc.DocumentNode.SelectNodes("//ul[@class='nav']/li");
                    List<Menu> menus = new List<Menu>();
                    if (hns != null && hns.Count > 0)
                    {
                        for (int i = 0; i < hns.Count; i++)
                        {
                            Menu menu = new Menu();
                            HtmlNode hn = hns[i];
                            HtmlDocument docA = new HtmlDocument();
                            docA.LoadHtml(hn.OuterHtml);
                            //查询超链接的html元素
                            HtmlNode hnA = docA.DocumentNode.SelectSingleNode("//a[@id]");
                            //获取image元素
                            HtmlNode hnImage = hnA.SelectSingleNode("//img");
                            //获取h2元素
                            HtmlNode hnText = hnA.SelectSingleNode("//h2");
                            //将获取的属性设置的menu对象
                            menu.Href = hnA == null ? null : hnA.Attributes["href"].Value;
                            if (hnImage != null)
                            {
                                menu.ImageAddress = hnImage.Attributes["src"].Value;
                                //通过address获取image
                                HttpBaseResult hbr = HttpHelper.HttpGetByteOrImage(ConfigModel.BaseUrl + "/" + menu.ImageAddress, ConfigModel.Cookies);
                                if(hbr.Code == 200)
                                {
                                    menu.Image = hbr.Image;
                                }
                            }
                            menu.Text = hnText == null ? null : hnText.InnerText;
                            //将menu添加到集合中
                            menus.Add(menu);
                        }
                        br.Code = Code.OK;
                        br.Object = menus;
                    }
                    else
                    {
                        br.Code = Code.NULL;
                        br.Message = "未能查询到导航菜单列表";
                    }

                }

                return br;
            }catch(Exception e)
            {
                return new BaseResult<List<Menu>>()
                {
                    Code = Code.NULL,
                    Message = e.Message + "\r\n" + e.StackTrace
                };
            }
        }

    }
}
